source ~/.bash_profile

# ssh配置
DEPLOY_USER=root
DEPLOY_PORT=22
# 钉钉告警配置
ACCESS_TOKEN=e9526eb327a1c1d731518db1593c623bcd240ee3fd4f0dee0feb63d0dabd6fe6

# 代码所在目录
cd ${SERVER_FOLDER}/${SERVER_NAME}
# 编译打包
# mvn clean package docker:build -DskipTests=true -Ddocker.host=http://${DEPLOY_HOST}:2375 -U -P ${PROFILE}
mvn clean package -DskipTests=true -U -P ${PROFILE}
# 检查mvn打包是否成功
if [ ! -f "target/${SERVER_NAME}.jar" ]; then
  echo "mvn编译打包失败. target/${SERVER_NAME}.jar 不存在."
  curl -fsSL https://gitee.com/hdzhangQAQ/twisly-riptide-doc/raw/master/shell/deploy/tool_send_ding.sh | \
    SERVER_LABEL=后端项目 \
    SERVER_NAME=${SERVER_NAME} \
    PROCESS=编译失败 \
    DEPLOY_HOST=${DEPLOY_HOST} \
    PROFILE=${PROFILE} \
    BUILD_USER=${BUILD_USER} \
    ACCESS_TOKEN=${ACCESS_TOKEN} \
  sh -
  exit -1
fi

for DEPLOY_HOST in ${DEPLOY_HOSTS[@]}; do
# 钉钉提醒-部署开始
curl -fsSL https://gitee.com/hdzhangQAQ/twisly-riptide-doc/raw/master/shell/deploy/tool_send_ding.sh | \
  SERVER_LABEL=后端项目 \
  SERVER_NAME=${SERVER_NAME} \
  PROCESS=部署开始 \
  DEPLOY_HOST=${DEPLOY_HOST} \
  PROFILE=${PROFILE} \
  BUILD_USER=${BUILD_USER} \
  ACCESS_TOKEN=${ACCESS_TOKEN} \
sh -

# 推送镜像
mvn docker:build -Dregistry.group=${REGISTRY_GROUP} -P ${PROFILE}
#mvn docker:push -Dregistry.group=${REGISTRY_GROUP} -P ${PROFILE}

CONTAINER_NAME=${SERVER_NAME}_${PROFILE}
# 移除已经存在的容器
CONTAINER_ID=$(ssh -p ${DEPLOY_PORT} ${DEPLOY_USER}@${DEPLOY_HOST} docker ps -a | grep ${CONTAINER_NAME} | awk '{print $1}')
ssh -p ${DEPLOY_PORT} ${DEPLOY_USER}@${DEPLOY_HOST} <<EOF
  if [ -n "${CONTAINER_ID}" ]; then
    echo "存在${CONTAINER_NAME}容器, CONTAINER_ID=${CONTAINER_ID}, 停止容器..."
    docker stop ${CONTAINER_ID}
    echo "容器${CONTAINER_NAME}-${CONTAINER_ID}停止成功"

    echo "存在${CONTAINER_NAME}容器, CONTAINER_ID=${CONTAINER_ID}, 开始删除..."
    docker rm ${CONTAINER_ID}
    echo "容器${CONTAINER_NAME}-${CONTAINER_ID}删除成功"
  fi
EOF

# 运行docker容器
ssh -p ${DEPLOY_PORT} ${DEPLOY_USER}@${DEPLOY_HOST} <<EOF
  echo "开始启动容器${CONTAINER_NAME} ..."
  docker run -it -e JAVA_OPTS='${JAVA_OPTS}' -e PROFILE='${PROFILE}' --name ${CONTAINER_NAME} -p ${SERVER_PORT}:${SERVER_PORT} -v /data/logs:/data/logs -d ${PROFILE}/${REGISTRY_GROUP}/${SERVER_NAME}:1.0.0-SNAPSHOT
  echo "${CONTAINER_NAME}容器启动完成"
EOF

# 钉钉提醒-部署成功
curl -fsSL https://gitee.com/hdzhangQAQ/twisly-riptide-doc/raw/master/shell/deploy/tool_send_ding.sh | \
  SERVER_LABEL=后端项目 \
  SERVER_NAME=${SERVER_NAME} \
  PROCESS=部署成功 \
  DEPLOY_HOST=${DEPLOY_HOST} \
  PROFILE=${PROFILE} \
  BUILD_USER=${BUILD_USER} \
  ACCESS_TOKEN=${ACCESS_TOKEN} \
sh -
done
